﻿
using LoLhelper.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.CompilerServices;
using System.Security.Principal;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LoLhelper
{
    public partial class Form1 : Form
    {
        private const string COMMAND = "wmic PROCESS WHERE name='LeagueClientUx.exe' GET commandline";//cmd命令
        private string _port = string.Empty;//端口
        private string _auth = string.Empty;//token
        private bool isTaskRunning = false;
        private bool isLogin = false;
        private CancellationTokenSource cancellationTokenSource;
        private SendHttp send = new SendHttp();
        private Random random = new Random();
        public Form1()
        {
            InitializeComponent();
            Switch.Enabled = false;
            InitAsync();
        }
        private async Task InitAsync()
        {
            if (IsAdministrator())
            {
                var result = CMD(COMMAND);
                Getportandauth(result);
                _port = _port.Remove(_port.Length - 1);
                _port = _port.Substring(_port.IndexOf("=") + 1);
                _auth = _auth.Remove(_auth.Length - 1);
                _auth = _auth.Substring(_auth.IndexOf("=") + 1);
                _auth = Convert.ToBase64String(Encoding.UTF8.GetBytes("riot:" + _auth));
                Parm.port = _port;
                Parm.token = _auth;
                User user = await send.GetUserInfo(Parm.port, Parm.token);
                if (user != null)
                {

                    label_level.Text = user.summonerLevel.ToString();
                    labe_name.Text = user.gameName.ToString() + "#" + user.tagLine.ToString();
                    byte[] data = await send.GetImgUrlAsync(user.profileIconId, Parm.port, Parm.token);
                    var ms = new System.IO.MemoryStream(data);
                    Bitmap bitmap = new Bitmap(ms);
                    // 在 PictureBox 控件中显示图像
                    atar.Image = bitmap;
                    Switch.Enabled = true;

                }
                await send.GetChampionInfo(Parm.port, Parm.token);


            }
            else { MessageBox.Show("请以管理员模式打开", "提示", MessageBoxButtons.OK); System.Environment.Exit(0); }


        }
        private void Getportandauth(string output)
        {
            Regex regex = new Regex("--remoting-auth-token=(.*?)[\"'\\s]");
            Regex regex1 = new Regex("--app-port=(.*?)[\"'\\s]");
            Match match = regex.Match(output);
            Match match1 = regex1.Match(output);
            if (match.Success)
            {
                _auth = match.Groups[0].Value;
            }
            if (match1.Success)
            {
                _port = match1.Groups[0].Value;
            }

        }
        public bool IsAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }
        public string CMD(string command)
        {
            Process pro = new Process();
            pro.StartInfo.FileName = "cmd.exe";             //cmd  
            pro.StartInfo.UseShellExecute = false;          //不显示shell  
            pro.StartInfo.CreateNoWindow = true;            //不创建窗口  
            pro.StartInfo.RedirectStandardInput = true;     //打开流输入  
            pro.StartInfo.RedirectStandardOutput = true;    //打开流输出  
            pro.StartInfo.RedirectStandardError = true;     //打开错误流  
            pro.Start();//执行  
            pro.StandardInput.WriteLine(command + "&exit");      //&exit运行完立即退出  
            pro.StandardInput.AutoFlush = true;             //清缓存  

            var str = pro.StandardOutput.ReadToEnd();            //读取输出  
            pro.WaitForExit();                              //等待程序执行完退出进程    
            pro.Close();//结束    
            return str;
        }

        //public async Task<bool> ListenGameStatusAsync()
        //{
        //    while (true)
        //    {
        //        await Task.Delay(10000);
        //        var status = await send.SearchMatchStatus(Parm.port, Parm.token);
        //        if(status==true) {return true;}
        //        else { return false;}

        //    }
        //}
        private void Switch_CheckedChanged(object sender, EventArgs e)
        {   
            if (Switch.Checked == true && isTaskRunning == false)
            {
                cancellationTokenSource = new CancellationTokenSource();
                var cancellationToken = cancellationTokenSource.Token;
                Task.Run(new Action(async () =>
                {
                    isTaskRunning = true;
                    while (true)
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            break;
                        }
                        var status = await send.SearchMatchStatus(Parm.port, Parm.token);
                        if (status == true)
                        {
                            await send.AcceptGame(Parm.port, Parm.token);
                        }

                        await Task.Delay(8000 + random.Next(1000, 2000));
                    }
                    isTaskRunning = false;


                }), cancellationToken);
            }
            else if (Switch.Checked == false)
            {
                cancellationTokenSource.Cancel();

            }

        }

        private void btn_refresh_BtnClick(object sender, EventArgs e)
        {
            Application.Restart();
        }



        private async void btn_search_BtnClick(object sender, EventArgs e)
        {
            if (content.Text.Length > 0)
            {
                try
                {
                    bool isGetPuuid = await send.GetPuuidAsync(Parm.port, Parm.token, content.Text.Trim());
                    listView.Items.Clear();
                    if (isGetPuuid)
                    {
                        var responseBody = await send.GetMatches(Parm.port, Parm.token, Parm.puuid);
                        Matches matches = JsonSerializer.Deserialize<Matches>(responseBody);
                        var games = matches.games.games;
                        foreach (var game in games)
                        {
                            ListViewItem item1 = new ListViewItem(DateTime.Parse(game.gameCreationDate).ToString("G"));
                            item1.Font = new Font("微软雅黑", 10);
                            item1.SubItems.Add(game.participants[0].stats.win ? "胜利" : "失败");
                            foreach (var item in Parm.list)
                            {
                                if (game.participants[0].championId == item.id)
                                {
                                    item1.SubItems.Add(item.name);
                                }
                            }

                            item1.SubItems.Add($"{game.participants[0].stats.kills}/{game.participants[0].stats.deaths}/{game.participants[0].stats.assists}");
                            string mode = string.Empty;
                            switch (game.gameMode)
                            {
                                case "URF":
                                    mode = "无限火力";
                                    break;
                                case "ARAM":
                                    mode = "大乱斗";
                                    break;
                                case "CLASSIC":
                                    mode = "峡谷";
                                    break;
                                default:
                                    mode = "自定义";
                                    break;
                            }
                            item1.SubItems.Add(mode);

                            listView.Items.Add(item1);
                        }
                    }

                }

                catch (Exception ex)
                {
                    // MessageBox.Show("未找到召唤师信息！", "提示", MessageBoxButtons.OK);

                    MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK);
                }

            }
            else
            {
                MessageBox.Show("请输入要查找的召唤师", "提示", MessageBoxButtons.OK);
            }
        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)//判断窗体是否为正常状态
            {
                notifyIcon1.Visible = false;            //隐藏托盘图标
            }
            else if (this.WindowState == FormWindowState.Minimized)//判断窗体是否为最小化状态
            {
                this.Hide();                                      //隐藏当前窗体
                notifyIcon1.Visible = true;                       //显示托盘图标
            }

        }

        private void 显示主页面ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();//显示当前窗体
            this.WindowState = FormWindowState.Normal;//还原窗体
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.ExitThread(); //退出当前程序
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            this.Show();//显示当前窗体
            this.WindowState = FormWindowState.Normal;//还原窗体
        }
    }


}
